package com.hellomaker.redismq.starter.impl;

import com.hellomaker.redismq.consume.listener.ListenerContainer;
import com.hellomaker.redismq.core.mq.SimpleRedisMQClient;
import com.hellomaker.redismq.starter.AutoConfigure;
import com.hellomaker.redismq.starter.config.parser.DelegateListenerAnnotationParser;
import com.hellomaker.redismq.starter.config.parser.ListenMessageParser;
import com.hellomaker.redismq.starter.config.parser.MessageListenerMethodParser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ConfigurableApplicationContext;

import java.util.Iterator;

public class ListenerAutoConfigure implements AutoConfigure {
    Logger logger = LoggerFactory.getLogger(ListenerAutoConfigure.class);

    @Override
    public void configure(ApplicationContext applicationContext) {
        try {
            SimpleRedisMQClient client = applicationContext.getBean(SimpleRedisMQClient.class);
            ListenerContainer<String, String> container = new ListenerContainer<>();
            DelegateListenerAnnotationParser delegateListenerAnnotationParser = new DelegateListenerAnnotationParser();
            delegateListenerAnnotationParser.applyParser(new ListenMessageParser(client, container));
            delegateListenerAnnotationParser.applyParser(new MessageListenerMethodParser(client, container));
//            Iterator<String> beanNamesIterator = applicationContext.getBeanNamesIterator();
            String[] beanDefinitionNames = applicationContext.getBeanDefinitionNames();
            for (String beanDefinitionName : beanDefinitionNames) {
                try {
                    Object bean = applicationContext.getBean(beanDefinitionName);
                    delegateListenerAnnotationParser.parseBean(bean.getClass(), bean, beanDefinitionName);
                } catch (Exception e) {
                    logger.error("parse bean exception:", e);
                }
            }
//            applicationContext.registerSingleton("simpleListenerContainer", container);
//            applicationContext.registerSingleton("delegateListenerAnnotationParser", delegateListenerAnnotationParser);
            logger.info("ListenerAutoConfigure configure ok, delegate parser generated.");
        } catch (Exception e) {
            logger.warn("ListenerAutoConfigure ignore");
        }
    }
}
